import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;

import javax.swing.JOptionPane;

import org.json.JSONObject;

public class JsonOp {
	SocketOp socket;
	public JsonOp(){
		socket = new SocketOp();
	}
	public void setIp(String remote_ip){
		socket.setIp(remote_ip);
	}
	public void setPort(int remote_port){
		socket.setPort(remote_port);
	}
	public JSONObject JSONrequest(JSONObject sendObject){
		String sendMessage = sendObject.toString();
		String recvMessage = null;
		JSONObject recvObject = null;
		try{
			recvMessage = socket.request(sendMessage);
			recvObject = new JSONObject(recvMessage);
		}catch(Exception e){
			
		}
		
		return recvObject;
	}
	public JSONObject JSONrequest(String sendMessage){
		String recvMessage = null;
		JSONObject recvObject = null;
		try{
			recvMessage = socket.request(sendMessage);
			recvObject = new JSONObject(recvMessage);
		}catch(Exception e){
			JOptionPane.showMessageDialog(null, "系统错误，错误代码：0110");
		}
		return recvObject;
	}
	public static String JSONReadFile(String fileName){
		String s = "";
		BufferedReader in = null;
		try{
			in = new BufferedReader(new FileReader(fileName));
			while(in.ready()){
				s += in.readLine();
			}
		}catch(Exception e){
			System.out.printf("JSONReadFile: " + e);
		}finally{
			try {
				in.close();
			} catch (Exception e) {
			}
		}
		return s;
	}
	public static boolean JSONWriteFile(String fileName,JSONObject obj){
		String s = null;
		BufferedWriter out = null;
		try{
			s = obj.toString();
			out = new BufferedWriter(new FileWriter(fileName));
			out.write(s);
			out.flush();
		}catch(Exception e){
			try {
				out.close();
			} catch (Exception e1) {}
			return false;
		}finally{
			try {
				out.close();
			} catch (Exception e1) {}
		}
		return true;
	}
}
